#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#
# 载入包
library(shiny)
library(tidyverse)
library(openxlsx)
library(GOplot)
# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("绘制弦图"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
	# 侧边栏
        sidebarPanel(
		# 文件上传
          fileInput('file1', 'Choose CSV File'),
          numericInput(inputId = "ni",label = "选择表格中的Sheet",value = 1),
		  # 以下为滑块
          sliderInput(inputId = "space",label = "基因间距",
                      value = 0.001, min = 0.001, max = 1),
          sliderInput(inputId = "gene.space",label = "基因名跟圆圈的相对距离",
                      value = 0.25, min = 0.25, max = 1),
          sliderInput(inputId = "gene.size",label = "基因名字体大小",
                      value = 4, min = 1, max = 20),
          sliderInput(inputId = "border.size",label = "线条粗细",
                      value = 0.1, min = 0.01, max = 5),
          sliderInput(inputId = "process.label",label = "term字体大小",
                      value = 8, min = 1, max = 40),
					  # 数字输入
          numericInput(inputId = "width",label = "pdf宽",value = 18),
          numericInput(inputId = "height",label = "pdf高",value = 16),
		  # 下载按钮
          downloadButton("downloadsimple", "Download")
        ),

        # Show a plot of the generated distribution
        mainPanel(
		# 主题窗格
          tabsetPanel(
            tabPanel("绘图",
                     plotOutput('Plot')
            ),
            tabPanel("表格",
                     tableOutput("Sheet")
                    )
        )
    ))
)

# Define server logic required to draw a histogram
server <- function(input, output) {
	# 读取文件
  contents <- reactive({
    
    # input$file1 will be NULL initially. After the user selects and uploads a 
    # file, it will be a data frame with 'name', 'size', 'type', and 'datapath' 
    # columns. The 'datapath' column will contain the local filenames where the 
    # data can be found.
    
    inFile <- input$file1
    
    if (is.null(inFile))
      return(NULL)
    
    read.xlsx(inFile$datapath,sheet = input$ni)
  })
  # 绘图函数
  plot_fun <- function(){
    ego <- contents()
    ego <- as.data.frame(ego)
    ego$Genes <- toupper(ego$Genes)
    gene <- separate_rows(ego,Genes,sep = ',') %>% select(Genes) %>% unique()
    gene$logFC <- seq(-0.0001*nrow(gene)-1, -1.0001, 0.0001) #根据实际情况定义基因的FC，一般为-1左右，不能相同，相同的FC画不出图形，例如有15个基因
    go=data.frame(Category = "All",ID = ego$Category,Term = ego$Term, Genes = ego$Genes, adj_pval = ego$pvalue)
    genelist <- data.frame(ID = gene$Genes, logFC = gene$logFC)
    row.names(genelist)=genelist[,1]
    circ <- circle_dat(go, genelist)
    termNum = nrow(go)   #限定term数目            
    geneNum = nrow(genelist) #限定基因数目
    chord <- chord_dat(circ, genelist[1:geneNum,], go$Term[1:termNum])
    GOChord(chord,
            space = input$space,           #基因之间的间距
            gene.order = 'logFC',    #按照logFC值对基因排序
            gene.space = input$gene.space,       #基因名跟圆圈的相对距离
            gene.size = input$gene.size,           #基因名字体大小，4或者5
            border.size = input$border.size,       #线条粗细
            process.label = input$process.label)     	 #term字体大小,8或者13
    
  } 

  # 表格函数
  output$Sheet <- renderTable({
    if (!is.null(contents()))
    {
      ego <- contents()
      ego <- as.data.frame(ego)
      ego
    }
  })
  # 绘图输出
  output$Plot <- renderPlot({
    if (!is.null(contents()))
      plot_fun()
  })
  

  # Downloadable csv of selected dataset ----
  # 下载函数
  output$downloadsimple <- downloadHandler(
    filename = function(){
      paste0("cluster", ".pdf")
    },
    
    content = function(file){
      pdf(file,width = input$width, height = input$height)
      print(plot_fun())
      dev.off()
    }
  )
}

# Run the application 
shinyApp(ui = ui, server = server)
